<!-- Created by jack on 2022/4/20 - 11:09 -->
<style scoped lang="less">
.volume-bar{
  width: 30px;
  height: 101px;
  background: #fff;
  box-shadow: 0 2px 5px 2px #d7d7d7;
  border-radius: 4px;
  box-sizing: border-box;
  padding: 8px 4px;
}
.bar-track{
  position: relative;
  height: 100%;
  width: 100%;
}
.bar-progress{
  position: absolute;
  background: #c33319;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  width: 4px;
  border-radius: 2px;
  height: v-bind(heightRatio);
  z-index: 2;
  &::after{
    position: absolute;
    content: '';
    width: 10px;
    height: 10px;
    left: 50%;
    transform: translate(-50%,-50%) ;
    background: #c33319;
    border-radius: 50%;
    z-index: 3;
  }
}
.bar-progress-back{
  position: absolute;
  background: rgba(210, 210, 210, 0.2);
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  width: 4px;
  border-radius: 2px;
  height: 100%;
  z-index: 1;
}
.active{
  &::after{
    transform:translate(-50%,-50%)  scale(1.2);
  }
}
</style>

<template>
    <div class="volume-bar">
      <div class="bar-track">
        <div class="bar-progress"
             id="netEasyMusic-volume-bar-progress"
             :class="{'active': mouseDown}"
             @mousedown="mouseDown = true"
             @click.capture="clickProgress"
        />
        <div class="bar-progress-back" ref="progress" @click="clickProgress"/>
      </div>
    </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, ref} from "vue";
const props = defineProps({
  value: { type: Number, default: 0},
  maxValue: { type: Number, default: 1},
})
const emit = defineEmits(['update:value'])
import {getDomPosition, getPointerPosition } from "@/helper";

const mouseDown = ref(false)
const progress = ref(null)
/** 高度比 */
const heightRatio = computed(() => (props.value *100 / props.maxValue) + '%')
/** 拖拽轴 */
const handleMouseMove = (event:MouseEvent) => {
  if(!mouseDown.value) return
  emit('update:value', calculateProgress(event))
}
/** 点击轴 */
const clickProgress = (event:MouseEvent) => emit('update:value', calculateProgress(event))
onMounted(() => {
  window.document.addEventListener('mousemove', handleMouseMove)
  window.document.addEventListener('mouseup', () => mouseDown.value = false)
})
/** 计算进度 */
const calculateProgress = (event:MouseEvent) => {
  const { top,height } = getDomPosition(progress.value,false) ?? { top:0, height:0 }
  const maxLength = top + height
  const { y } = getPointerPosition(event)
  const value = (maxLength - y) / height * props.maxValue
  return value > 1 ? 1 : value < 0 ? 0 : value
}
</script>
